package cn.bas;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient // nacos 注解 能够被注册中心发现，实现自动注册服务
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    /*
    RestTemplateConfiguration 配置类，创建 RestTemplate Bean。
    RestTemplate 是 Spring 提供的 HTTP 调用模板工具类，可以方便我们稍后调用服务提供者的 HTTP API。
     */
    @Configuration
    public class RestTemplateConfiguration {
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }

    }

    @RestController
    static class TestController{

        @Autowired
        private DiscoveryClient discoveryClient; // 获得nacos对象

        @Autowired
        private RestTemplate restTemplate; // 获得远程调用对象

        @Autowired
        private LoadBalancerClient loadBalancerClient; // 获得负载均衡对象

        @GetMapping("/hello")
        public String hello(String name){
            ServiceInstance instance; // 获得注册的服务对象
            if(true){
                List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider");// 通过应用服务名获得对应的实例列表
                instance = instances.size()>0?instances.get(0):null;
            }else{
                // 选择服务ID，实现负载均衡
                instance = loadBalancerClient.choose("demo-provider");
            }
            if(instance==null){
                throw new IllegalStateException("获取不到实例");
            }

            String targetUri = instance.getUri()+"/echo?name="+name;
            String response =  restTemplate.getForObject( targetUri,String.class );
            return "consumer : "+response;
        }
    }

}